#pragma once

#include <iostream>
#include <string>
#include <memory>
#include <sys/epoll.h>
#include "Log.hpp"
#include "Socket.hpp"

#define MAX 4096
using namespace SocketModule;
using namespace LogModule;

const int gdefaultfd = -1;

class EpollServer
{
    static const int revs_num = 64;
public:
    EpollServer(uint16_t port)
        : _port(port), _listen_socket(std::make_unique<TcpSocket>()), _isrunning(false), _epfd(gdefaultfd)
    {
    }

    void Init()
    {
        _listen_socket->BuildTcpSocketMethod(_port);
        // 1.创建epoll模型
        _epfd = epoll_create(256);
        if (_epfd < 0)
        {
            LOG(LogLevel::ERROR) << "epoll create error";
            Die(EPOLL_CREATE_ERROR);
        }
        LOG(LogLevel::DEBUG) << "epoll create success: " << _epfd;

        // 2.将listensockfd添加到epoll模型中
        struct epoll_event ev;
        ev.events = EPOLLIN;
        ev.data.fd = _listen_socket->Fd();
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, _listen_socket->Fd(), &ev);
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_ctl error";
            Die(EPOLL_CTL_ERROR);
        }
    }

    void Loop()
    {
        _isrunning = true;
        while (_isrunning)
        {
            int timeout = -1;
            int n = epoll_wait(_epfd, _revs, revs_num, timeout);
            switch (n)
            {
            case 0:
                std::cout << "time out..." << std::endl;
                break;
            case -1:
                perror("epoll_wait");
                break;
            default:
                std::cout << "有事件就绪了..." << std::endl;
                Dispatcher(n); // 把已经就绪的fd，派发给指定的模块
                break;
            }
        }
        _isrunning = false;
    }

    void Accepter()
    {
        InetAddr client;
        // 不会阻塞了，也就是不用等了，只用拷贝就行
        int newfd = _listen_socket->Accepter(&client);
        if (newfd < 0)
            return;
        else
        {
            std::cout << "获得了一个新链接: " << newfd << ", client info: " << client.Addr() << std::endl;
            struct epoll_event ev;
            ev.data.fd = newfd;
            ev.events = EPOLLIN;
            int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, newfd, &ev);
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_ctl error";
                close(newfd);
            }
        }
    }

    void Recver(int fd)
    {
        char buffer[1024];
        ssize_t n = recv(fd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client# " << buffer << std::endl;

            std::string message = "echo# ";
            message += buffer;
            send(fd, message.c_str(), message.size(), 0);
        }
        else if (n == 0)
        {
            LOG(LogLevel::DEBUG) << "客户端退出..., sockfd: " << fd;
            // close(fd);
            // 把fd从epoll中移除，必须保证fd是合法的
            // 应该先把fd从epoll中移除，在关闭fd
            int n = epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_ctl error";
                Die(EPOLL_CTL_ERROR);
            }
            LOG(LogLevel::DEBUG) << "epoll_ctl success: " << fd;
            close(fd);
        }
        else
        {
            LOG(LogLevel::DEBUG) << "客户端读取错误..., sockfd: " << fd;
            // close(fd);
            // 把fd从epoll中移除
            int n = epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_ctl error";
                Die(EPOLL_CTL_ERROR);
            }
            LOG(LogLevel::DEBUG) << "epoll_ctl success: " << fd;
            close(fd);
        }
    }

    void Dispatcher(int rnum)
    {
        for (int i = 0; i < rnum; i++)
        {
            if (_revs[i].data.fd == _listen_socket->Fd())
            {
                if (_revs[i].events == EPOLLIN)
                {
                    Accepter();
                }
            }
            else
            {
                if (_revs[i].events == EPOLLIN)
                {
                    Recver(_revs[i].data.fd);
                }
            }
        }
    }
    ~EpollServer()
    {
        close(_listen_socket->Fd());
        if (_epfd) close(_epfd);
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listen_socket;
    bool _isrunning;
    int _epfd;
    struct epoll_event _revs[revs_num];
};
